package com.crr.controller;

import cn.hutool.core.bean.BeanUtil;
import com.crr.bean.Customer;
import com.crr.common.bean.PageBean;
import com.crr.common.bean.ResultBean;
import com.crr.common.controller.BaseController;
import com.crr.query.CustomerQuery;
import com.crr.service.CustomerService;
import com.crr.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Api(tags = "客户管理")
@RequestMapping("/v1")
@RestController
public class CustomerController extends BaseController {
    @Autowired
    CustomerService customerService;
    @Autowired
    UserService userService;

    @ApiOperation("查询客户")
    @PostMapping("/customer/query")
    public ResultBean query(@RequestBody CustomerQuery customerQuery){
        PageBean bean = customerService.query(BeanUtil.beanToMap(customerQuery));
        return success("客户列表",bean);
    }
    @PutMapping("/customer")
    @ApiOperation("修改客户")
    public ResultBean update( @RequestBody Customer customer){
        int res = customerService.update(customer);
        return updateResult(res);
    }
    @ApiOperation("删除客户")
    @DeleteMapping("/customer")
    public ResultBean delete(int id){
        int res = customerService.delete(id);
        return deleteResult(res);
    }
    @ApiOperation("新增客户")
    @PostMapping("/customer")
    public ResultBean save( @RequestBody Customer customer){
        int res = userService.queryUserByAccount(customer.getUser().getUsername());
        if(res==1){
            return fail("客户名已被占用！");
        }
        int rs = customerService.save(customer);
        return saveResult(rs);
    }
}
